import { useStorage } from '@vueuse/core'

export const fetchFn = async (path: string, body?: any): Promise<any> => {
  try {
    const apiUrl = import.meta.env.VITE_API_URL + path

    const queryString = new URLSearchParams(body).toString()

    const response = await fetch(`${apiUrl}?${queryString}`, {
      method: 'GET',
    })

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`)
    }

    const { data } = await response.json()
    return data
  } catch (error) {
    console.error('Error fetching data:', error)
    throw error
  }
}

/**
 * AGV 状态
 */
const agvStatus = useStorage('agv-status', [])

/**
 * 升降台状态
 */
const liftStatus = useStorage('lift-status', [])

/**
 * 自动门状态
 */
const doorStatus = useStorage('door-status', [])

/**
 * 自动门状态
 */
const taskStatus = useStorage<any>('task-status', {})

export const queryData = async () => {
  agvStatus.value = await fetchFn('/dc-robot/v1/list')

  const liftData = await fetchFn(`/lift/v1/list`)
  liftStatus.value = liftData.list || []

  const doorData = await fetchFn(`/dc-point/v1/list`, { type: 1 })
  doorStatus.value = doorData.list || []

  const taskData = await fetchFn(`/dc-task/v1/list`)
  taskStatus.value = taskData.list?.[0] || {}
}

queryData()

setInterval(queryData, import.meta.env.VITE_INTERVAL_TIME)
